package com.qianfeng.smartplatform.event.listeners;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.smartplatform.mapper.UserOnlineMapper;
import com.qianfeng.smartplatform.pojo.LoginLog;
import com.qianfeng.smartplatform.pojo.UserOnline;
import com.qianfeng.smartplatform.security.BaseUser;
import com.qianfeng.smartplatform.service.UserLoginLogService;
import com.qianfeng.smartplatform.service.UserOnlineService;
import com.qianfeng.smartplatform.service.UserService;
import com.qianfeng.smartplatform.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by Jackiechan on 2021/12/21/下午9:55
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class UserLoginListener {

    private UserService userService;

    private UserLoginLogService userLoginLogService;

    private UserOnlineService userOnlineService;
    private ThreadPoolExecutor complateFutureExecutor;

    @Autowired
    public void setComplateFutureExecutor(ThreadPoolExecutor complateFutureExecutor) {
        this.complateFutureExecutor = complateFutureExecutor;
    }
    @Autowired
    public void setUserOnlineService(UserOnlineService userOnlineService) {
        this.userOnlineService = userOnlineService;
    }

    @Autowired
    public void setUserLoginLogService(UserLoginLogService userLoginLogService) {
        this.userLoginLogService = userLoginLogService;
    }

    private UserOnlineMapper userOnlineMapper;


    @Autowired
    public void setUserOnlineMapper(UserOnlineMapper userOnlineMapper) {
        this.userOnlineMapper = userOnlineMapper;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }



    /**
     * 登录成功的事件
     * @param event
     */
    @EventListener
  //  @Async
    public void onEvent(AuthenticationSuccessEvent event) {
        System.err.println("事件====>"+Thread.currentThread());
        BaseUser baseUser = (BaseUser) event.getAuthentication().getPrincipal();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
        //登录成功的话更新状态
        Date loginTime = new Date();
        String ip = RequestUtil.getRemoteHost(request);
        CompletableFuture<Void> update = CompletableFuture.runAsync(() -> {
            userService.updateUserLoginInfoByUserName(baseUser.getUsername(), loginTime, ip);
        },complateFutureExecutor);
        CompletableFuture<Void> addLog = CompletableFuture.runAsync(() -> {
            //更新登录操作数据
            LoginLog loginLog = new LoginLog();
            loginLog.setLoginName(baseUser.getUsername());
            loginLog.setLoginTime(loginTime);
            loginLog.setBrowser(osAndBrowserInfo.get("browser"));
            loginLog.setIpaddr(ip);
            loginLog.setMsg("登录成功");
            loginLog.setOs(osAndBrowserInfo.get("os"));
            loginLog.setStatus("1");
            loginLog.setLoginLocation(RequestUtil.getLocationByIp(ip));
//            loginLog.setLoginLocation("暂时先写一个");
//            loginLogMapper.insertSelective(loginLog);
            userLoginLogService.addLoginLog(loginLog);
        },complateFutureExecutor);

        CompletableFuture<Void> onLine = CompletableFuture.runAsync(() -> {
            UserOnline userOnline = new UserOnline();
            userOnline.setSessionid(request.getSession().getId());
            userOnline.setLoginName(baseUser.getUsername());
            userOnline.setBrowser(osAndBrowserInfo.get("browser"));
            userOnline.setOs(osAndBrowserInfo.get("os"));
            userOnline.setIpaddr(ip);
//            userOnline.setLoginLocation("暂时先写一个");
            userOnline.setLoginLocation(RequestUtil.getLocationByIp(ip));
            userOnline.setStatus("1");
            userOnline.setStartTimestamp(loginTime);
            userOnline.setLastAccessTime(loginTime);
            userOnline.setExpireTime(30);//过期时间30分钟
            userOnlineService.addOrUpdateOnline(userOnline);
        },complateFutureExecutor);


        CompletableFuture.allOf(update, addLog,onLine);
    }
    //登录失败的事件
    @EventListener
 //   @Async
    public void onEvent(AbstractAuthenticationFailureEvent event) {
        Object username = event.getAuthentication().getPrincipal();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
        //登录成功的话更新状态
        Date loginTime = new Date();
        String ip = RequestUtil.getRemoteHost(request);
        CompletableFuture.runAsync(() -> {
            //更新登录操作数据
            LoginLog loginLog = new LoginLog();
            loginLog.setLoginName((String) username);
            loginLog.setLoginTime(loginTime);
            loginLog.setBrowser(osAndBrowserInfo.get("browser"));
            loginLog.setIpaddr(ip);
            loginLog.setMsg(event.getException().getMessage());
            loginLog.setOs(osAndBrowserInfo.get("os"));
            loginLog.setStatus("0");
            loginLog.setLoginLocation(RequestUtil.getLocationByIp(ip));
            //loginLog.setLoginLocation("暂时先写一个");
//            loginLogMapper.insertSelective(loginLog);
            userLoginLogService.addLoginLog(loginLog);
        },complateFutureExecutor);

    }


}
